require "readline"
require "thrift/transport/thttpclient"
require "thrift/protocol/binaryprotocol"
require "thrift/struct"
require "Evernote/EDAM/UserStore"
require "Evernote/EDAM/UserStore_constants.rb"
require "Evernote/EDAM/NoteStore"
require "Evernote/EDAM/Limits_constants.rb"

#
# Configure these based on the API key you received from Evernote
#
consumerKey = "your-api-key-here!"
consumerSecret = "your-api-secret-here!"
username = "your-username"
password = "your-password"

edamBaseUrl = "https://stage.evernote.com"

userStoreUrl = edamBaseUrl + "/edam/user"
userStoreTransport = Thrift::HTTPClient.new(userStoreUrl)
userStoreProtocol = Thrift::BinaryProtocol.new(userStoreTransport)
userStore = Evernote::EDAM::UserStore::UserStore::Client.new(userStoreProtocol)

versionOK = userStore.checkVersion("Ruby EDAMTest",
                                Evernote::EDAM::UserStore::EDAM_VERSION_MAJOR,
                                Evernote::EDAM::UserStore::EDAM_VERSION_MINOR)
puts "Is my EDAM protocol version up to date?  #{versionOK}"
if (!versionOK)
  exit(1)
end

authResult = userStore.authenticate(username, password,
                                    consumerKey, consumerSecret)
user = authResult.user
authToken = authResult.authenticationToken
puts "Authentication was successful for #{user.username}"
puts "Authentication token = #{authToken}"

noteStoreUrl = edamBaseUrl + "/edam/note/" + user.shardId
noteStoreTransport = Thrift::HTTPClient.new(noteStoreUrl)
noteStoreProtocol = Thrift::BinaryProtocol.new(noteStoreTransport)
noteStore = Evernote::EDAM::NoteStore::NoteStore::Client.new(noteStoreProtocol)

notebooks = noteStore.listNotebooks(authToken)
puts "Found #{notebooks.size} notebooks:"
defaultNotebook = notebooks[0]
notebooks.each { |notebook| 
  puts "  * #{notebook.name}"
  if (notebook.defaultNotebook)
    defaultNotebook = notebook
  end
}

puts
puts "Creating a new note in the default notebook: #{defaultNotebook.name}"
puts
note = Evernote::EDAM::Type::Note.new()
note.notebookGuid = defaultNotebook.guid
note.title = Readline.readline("Note title?  ").strip()
note.content = '<?xml version="1.0" encoding="UTF-8"?>' +
  '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml.dtd">' +
  '<en-note>' +
  Readline.readline("Well-formed XHTML note content?  ").strip() +
  '</en-note>'
note.created = Time.now.to_i * 1000
note.updated = note.created

createdNote = noteStore.createNote(authToken, note)

puts "Note was created, GUID = #{createdNote.guid}"

